package com.handpay.nocardpay.baselibrary.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;

/**
 * 注意，使用银行卡控件时设置值请使用类中setText方法设置值
 */
public class BankCardNoEditTextView extends RelativeLayout {
    private Context mContext;
    private EditText bank_card_no_et;
    private ImageView iv_clear;
    private String d = "";
    private int mTextColor;//textColor
    private int mHintTextColor;//hintColor
    protected int defaultTextColor = Color.WHITE;//default text and hint Color
    volatile private boolean isRun = false;
    private int rightDeleteIcon = -1;
    private String edt_hint = "";
    //是否聚焦
    private boolean hasFocus = false;
    private BankCardInputListener bankCardInputListener = null;
    private boolean bEnable = true;

    /**
     * 失去焦点并且 输入大于11位时回调
     */
    public interface BankCardInputListener {
        /**
         * 条件满足，自动发起卡bin查询
         */
        void autoQueryCardBin(String cardno);
    }

    public BankCardNoEditTextView(Context context) {
        this(context, null);
    }

    public BankCardNoEditTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BankCardNoEditTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        setCustomAttributes(attrs);
        init();
    }

    private void setCustomAttributes(AttributeSet attrs) {
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.BankCardNoEditTextView);
        try {
            if (typedArray != null) {
                rightDeleteIcon = typedArray.getResourceId(R.styleable.BankCardNoEditTextView_rightDeleteImage, -1);
                int hintid = typedArray.getResourceId(R.styleable.BankCardNoEditTextView_hint, -1);
                edt_hint = getResources().getString(hintid);
                mHintTextColor = typedArray.getColor(R.styleable.BankCardNoEditTextView_HintTextColor, getResources().getColor(R.color.text_hint_color));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            typedArray.recycle();
        }
    }

    private Drawable mClearDrawable = null;

    // TODO: 2017/8/14 图标比例缩小需要做 
    @SuppressLint("NewApi")
    private void init() {
        View root = LayoutInflater.from(mContext).inflate(R.layout.layout_bank_card_no_edit_text_view, this);
        iv_clear = (ImageView) root.findViewById(R.id.iv_clear);
        iv_clear.setVisibility(View.INVISIBLE);
        if (rightDeleteIcon != -1) {
            iv_clear.setBackgroundResource(rightDeleteIcon);
            mClearDrawable = iv_clear.getBackground();
            Drawable temp_icon = zoomDrawable(mClearDrawable);
            iv_clear.setBackground(null);
            iv_clear.setImageDrawable(temp_icon);
        }
        bank_card_no_et = (EditText) this.findViewById(R.id.bank_card_no_et);
        bank_card_no_et.setHintTextColor(mHintTextColor);

        if (!TextUtils.isEmpty(edt_hint)) {
            bank_card_no_et.setHint(edt_hint);
        }
        bank_card_no_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (isRun) {
                    isRun = false;
                    return;
                }
                isRun = true;

                d = "";
                String newStr = s.toString();
                newStr = newStr.replace(" ", "");

                int index = 0;
                while ((index + 4) < newStr.length()) {
                    d += (newStr.substring(index, index + 4) + " ");
                    index += 4;
                }
                d += (newStr.substring(index, newStr.length()));
                int i = getEditTextCursorIndex(bank_card_no_et);

                bank_card_no_et.setText(d);

                try {

                    if (i % 5 == 0 && before == 0) {
                        if (i + 1 <= d.length()) {
                            bank_card_no_et.setSelection(i + 1);
                        } else {
                            bank_card_no_et.setSelection(d.length());
                        }
                    } else if (before == 1 && i < d.length()) {
                        bank_card_no_et.setSelection(i);
                    } else if (before == 0 && i < d.length()) {
                        bank_card_no_et.setSelection(i);
                    } else {
                        bank_card_no_et.setSelection(d.length());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // **获取EditText光标所在的位置*//*
            public int getEditTextCursorIndex(EditText editText) {
                return editText.getSelectionStart();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String newStr = s.toString();
                newStr = newStr.replace(" ", "");
                if (newStr.length() > 0) {
                    setRightIconVisibility(false);
                } else {
                    setRightIconVisibility(true);
                }
            }
        });

        bank_card_no_et.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean mhasFocus) {
                hasFocus = mhasFocus;
                if (!hasFocus) {
                    setRightIconVisibility(true);
                    if (!TextUtils.isEmpty(bank_card_no_et.getText()) && bank_card_no_et.getText().toString().length() >= 13) {//空格算上11+2
                        if (bankCardInputListener != null) {
                            String temp = bank_card_no_et.getText().toString().trim();
                            temp = temp.replace(" ", "");
                            bankCardInputListener.autoQueryCardBin(temp);
                        }
                    }
                } else {
                    if (bank_card_no_et.getText().length() > 1) {
                        setRightIconVisibility(false);
                    }
                }
            }
        });

        OnClickListener clearListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                setEnabled(true);
                bank_card_no_et.setText("");
            }
        };
        iv_clear.setOnClickListener(clearListener);
        if (!bank_card_no_et.hasFocus()) {
            iv_clear.setVisibility(View.INVISIBLE);
        }
    }

    public Editable getText() {
        return bank_card_no_et.getText();
    }


    /**
     * 设置 EditText ok键动作，并且动作监听
     * @param mImeOptions
     */
    public void setImeOptions(int mImeOptions){
        if(mImeOptions!=-1){
            bank_card_no_et.setImeOptions(mImeOptions);
        }
        bank_card_no_et.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //按物理back会关闭键盘，看成焦点失去
                if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_BACK)) {
                    bank_card_no_et.clearFocus();
                    return true;
                }
                return false;
            }
        });
        bank_card_no_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                HPLog.i(HPLog.LFP_TAG,"actionId="+actionId);
                boolean isOK = false;
                switch (actionId) {
                    case EditorInfo.IME_ACTION_DONE:
                        HPLog.i(HPLog.LFP_TAG,"IME_ACTION_DONE");
                        bank_card_no_et.clearFocus();
                        InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        if(imm.isActive()){
                            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0 );
                        }
                        isOK = true;
                        break;
                    case EditorInfo.IME_ACTION_NEXT:
                        HPLog.i(HPLog.LFP_TAG,"IME_ACTION_NEXT");
                        break;
                    default:
                        isOK = false;
                        break;
                }
                return isOK;
            }
        });
    }

    /**
     * 设置图标是否隐藏
     * 当前没获取焦点不处理
     *
     * @param iconVisibility true 表示隐藏，false 表示显示
     */
    public void setRightIconVisibility(boolean iconVisibility) {
//        HPLog.i(HPLog.LFP_TAG,"setRightIconVisibility::iconVisibility="+iconVisibility);
        if (iv_clear != null) {
            iv_clear.setVisibility(iconVisibility ? View.INVISIBLE : View.VISIBLE);
        }
    }

    /**
     * 设置银行卡号值，只有光标选中显示删除按钮
     */
    public void setText(CharSequence text) {
        String d = "";
        String newStr = text.toString();
        newStr = newStr.replace(" ", "");
        int index = 0;
        while ((index + 4) < newStr.length()) {
            d += (newStr.substring(index, index + 4) + " ");
            index += 4;
        }
        d += (newStr.substring(index, newStr.length()));
        bank_card_no_et.setText(d);
        if (!bank_card_no_et.hasFocus()) {
            iv_clear.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 设置银行卡号值，光标没有选中也自动显示删除按钮
     */
    public void setTextWithOutFocus(CharSequence text) {
        String d = "";
        String newStr = text.toString();
        newStr = newStr.replace(" ", "");
        int index = 0;
        while ((index + 4) < newStr.length()) {
            d += (newStr.substring(index, index + 4) + " ");
            index += 4;
        }
        d += (newStr.substring(index, newStr.length()));
        bank_card_no_et.setText(d);

    }


    public void setTextColor(int color) {
        bank_card_no_et.setTextColor(color);
    }

    public void setBankCardInputListener(BankCardInputListener bankCardInputListener) {
        this.bankCardInputListener = bankCardInputListener;
    }

    private Drawable zoomDrawable(Drawable drawable) {
        //这里很奇怪，应该是缩小图片，但是按比例缩小显示不正常
        Bitmap oldbmp = drawableToBitmap(drawable); // drawable 转换成 bitmap
        Matrix matrix = new Matrix();   // 创建操作图片用的 Matrix 对象
        float scaleWidth = 2.0f;   // 计算缩放比例
        float scaleHeight = 2.0f;
        matrix.postScale(scaleWidth, scaleHeight);// 设置缩放比例
        Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight(), matrix, false);// 建立新的 bitmap ，其内容是对原 bitmap 的缩放后的图
        return new BitmapDrawable(newbmp);       // 把 bitmap 转换成 drawable 并返回
    }

    private Bitmap drawableToBitmap(Drawable drawable) // drawable 转换成 bitmap
    {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        HPLog.i(HPLog.LFP_TAG, "drawableToBitmap::with=" + width + ",height=" + height);
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;         // 取 drawable 的颜色格式
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }


    @Override
    public void setEnabled(boolean enabled) {
        bEnable = enabled;
        bank_card_no_et.setEnabled(bEnable);
    }

    @Override
    public boolean isEnabled() {
        return bEnable;
    }
}
